package com.le.enhance.class2;

import org.junit.Test;

import java.util.Arrays;
import java.util.LinkedList;

/**
 * 滑动窗口问题,给定窗口大小m,生成窗口的最大值数组   时间复杂度O(n)
 * 采用双向链表  保证从左到右 从大到小顺序,添加元素从最后添加
 */
public class Code_01_slideWindowMaxArray {

    // 暴力解决
    public static int[] getMaxArray1(int[] arr, int m) {
        if (arr == null || m < 1 || arr.length < m) {
            return null;
        }
        if (arr.length == 2) {
            return new int[]{Math.max(arr[0], arr[1])};
        }
        int[] res = new int[arr.length - m + 1];
        int index = 0;
        int i = 0;
        int j = 1;
        while (i < arr.length && (j + 1) < arr.length) {
            j++;
            int max = Integer.MIN_VALUE;
            for (int p = i; p != j + 1; p++) {
                max = Math.max(arr[p], max);
            }
            res[index++] = max;
            i++;
        }
        return res;
    }

    public static int[] getMaxArray(int[] arr, int m) {
        if (arr == null || m < 1 || arr.length < m) {
            return null;
        }
        int[] res = new int[arr.length - m + 1]; // 最大值数组
        int index = 0;
        LinkedList<Integer> list = new LinkedList<>();
        for (int i = 0; i < arr.length; i++) {
            while (!list.isEmpty() && arr[list.peekLast()] <= arr[i]) {
                list.pollLast();
            }
            list.addLast(i);
            if (list.peekFirst() == i - m) { // 判断头部元素是否过期,过期则删除
                list.pollFirst();
            }
            if (i >= m - 1) {
                res[index++] = arr[list.peekFirst()];
            }
        }
        return res;
    }

    @Test
    public void test() {
        int[] arr = {4, 3, 5, 4, 3, 3, 6, 7};
//        int[] maxArray = getMaxArray(arr, 3);
        int[] maxArray1 = getMaxArray1(arr, 3);
        System.out.println(Arrays.toString(maxArray1));
    }
}
